/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.chalmers.se.tda367.database;

import edu.chalmers.se.tda367.model.User;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import edu.chalmers.se.tda367.database.Database;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import edu.chalmers.se.tda367.main.Pluggis;

/**
 *
 * @author pierrereimertz
 */
public class DatabaseController {

    //private  scanner;
    public DatabaseController() {
    }

    public static void addUserToDatabase(User u) throws FileNotFoundException, IOException {
        Database db = Database.getInstance();
        String s = u.toDatabaseString() + "\n";
        System.out.println("i DbController(): " + s);

        db.addToTempDbFileString(s);

        db.add(u);

        Writer out = new OutputStreamWriter(new FileOutputStream("database/database.data"));


        out.write(db.getTempDbFileString());
        out.close();
    }

    public static void removeUserfromDatabase(User u) throws FileNotFoundException, IOException {
        Database db = Database.getInstance();
        db.resetTempFile();


        //Remove from ArrayList
        for (int i = 0; i < db.getDatabase().size(); i++) {
            if (u.equals(db.getDatabase().get(i))) {
                db.remove(i);
                break;
            }
        }

        //Remove from database.data
        Scanner scanner = new Scanner(new File("database/database.data"));
        scanner.useDelimiter(System.getProperty("line.separator"));

        while (scanner.hasNext()) {
            String st = scanner.next();

            if (!(u.toDatabaseString().equals(st))) {
                db.addToTempDbFileString(st + "\n");
            }
        }


        Writer out = new OutputStreamWriter(new FileOutputStream("database/database.data"));

        out.write(db.getTempDbFileString());
        out.close();
        scanner.close();
        Pluggis.repaintViews();


        //db.addToTempDbFileString(s);


    }
}
